<template>
	<div class="xmlIndex">
		<div id="">
			<h2>js读取xml</h2>
			<el-button @click="read">读取</el-button>
		</div>
		<!-- <code id="code1" ref="code1">{{ data }}</code> -->
		<div id="code1" ref="code1"  v-html="data">
			
		</div>
	</div>
</template>

<script>
import { xmlData ,jsonData,jsonData2} from '@/assets/js/testData.js';
export default {
	name: 'xmlIndex',
	data() {
		return {
			data: ''
		};
	},

	mounted() {},
	methods: {
		read() {
			// console.log("read  xml data is "+this.data);
			this.data = xmlData;
			let xmlDoc = null;
			// this.data.replaceAll('/n  ',"")
			// console.log("this.data",this.data)
			// let code1 = document.getElementById("code1");
			// console.log("code1",this.$refs.code1)
			// console.log("this.$refs.code1",code1.innerText)
			// xmlDoc = this.xmlStrToJsonObj(this.data)
			var parser = new DOMParser();
			    var doc=parser.parseFromString(this.data, "text/xml");
			console.log('xmlDoc', xmlDoc);
			console.log('jsonData', jsonData);
			
			console.log('jsonData JSON', JSON.parse(jsonData));
			console.log('jsonData2', jsonData2);
			
			console.log('jsonData2 JSON', JSON.parse(jsonData2));
		
		},
		xmlStrToJsonObj(xmlStr){
			 var xmlObj = this.xmlStrToXmlObj(xmlStr);
			    var jsonObj = {};
			    if (xmlObj.childNodes.length > 0) {
			        jsonObj = this.xmlObjToJsonObj(xmlObj.childNodes);
			    }
			    return jsonObj;
		},
		xmlStrToXmlObj(xmlStr) {
		    var xmlObj = {};
		    if (document.all) {
		        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
		        xmlDom.loadXML(xmlStr);
		        xmlObj = xmlDom;
		    } else {
		        xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
		    }
		    return xmlObj;
		
		},
		xmlObjToJsonObj(xmlNodes) {
		
		    var obj = {};
		    if (xmlNodes.length == 0) {
		        obj = '';
		    } else {
		        for (var i = 0; i < xmlNodes.length; i++) {
		            var node = xmlNodes[i];
		            if (typeof node.tagName == "undefined" || node.nodeName == "#text") {
		                obj = node.nodeValue;
		            } else {
		                var key = node.tagName;
		                var value = this.xmlObjToJsonObj(node.childNodes)
		                obj[key] = value;
		            }
		
		
		        }
		
		    }
		    return obj;
		}
		
		 
	}
};
</script>
<style scoped></style>
